#pragma once

#include <iostream>
#include <memory>
#include <unistd.h>
#include <sys/epoll.h>
#include "Socket.hpp"
#include "Log.hpp"

using namespace SocketModule;
using namespace LogModule;

class EpollServer
{
    const static int size = 64;
    const static int defaultfd = -1;

public:
    EpollServer(int port)
        : _listenSock(std::make_unique<TcpSocket>()), _isrunning(false), _epfd(defaultfd)
    {
        _listenSock->BuildTcpSocketMethod(port);
        // 创建epoll模型
        _epfd = epoll_create(256);
        if (_epfd < 0)
        {
            LOG(LogLevel::FATAL) << "epoll_create error";
            exit(EPOLL_CREATE_ERR);
        }
        LOG(LogLevel::INFO) << "epoll_create success: " << _epfd;

        // 调用epoll_ctl监听_listenSock的读事件
        // 强化事件的认知概念
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = _listenSock->Fd();

        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listenSock->Fd(), &ev);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "add listensockfd failed";
            exit(EPOLL_CTL_ERR);
        }
    }

    void Start()
    {
        int timeout = -1;
        _isrunning = true;
        while (_isrunning)
        {
            int n = epoll_wait(_epfd, _revs, size, timeout);
            switch (n)
            {
            case 0:
                LOG(LogLevel::DEBUG) << "timeout...";
                break;
            case -1:
                LOG(LogLevel::ERROR) << "epoll error";
                break;
            default:
                Dispatcher(n);
                break;
            }
        }
        _isrunning = false;
    }

    void Dispatcher(int rnum)
    {
        // LT: epoll默认水平触发模式-
        LOG(LogLevel::DEBUG) << "event ready ...";
        for (int i = 0; i < rnum; i++)
        {
            int sockfd = _revs[i].data.fd;
            uint32_t revent = _revs[i].events;
            if (revent & EPOLLIN)
            {
                if (sockfd == _listenSock->Fd())
                {
                    Accepter();
                }
                else
                {
                    Recver(sockfd);
                }
            }

            // if(revent & EPOLLOUT)
            // {

            // }
        }
    }

    void Accepter()
    {
        InetAddr client;
        int sockfd = _listenSock->Accept(&client);
        if (sockfd >= 0)
        {
            LOG(LogLevel::INFO) << "get a new link, sockfd: " << sockfd << ", client is: " << client.StringAddr();
            
            //将新到来的连接（套接字）让epoll监听
            struct epoll_event ev;
            ev.events = EPOLLIN;
            ev.data.fd = sockfd;
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &ev);
            if(n < 0)
            {
                LOG(LogLevel::WARNING) << "add listensockfd failed";
            }
            else
            {
                LOG(LogLevel::WARNING) << "add listensockfd failed";
            }
        }
    }

    void Recver(int sockfd)
    {
        char buffer[1024];
        ssize_t n = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say@ " << buffer << std::endl;
        }
        else if(n == 0)
        {
            LOG(LogLevel::INFO) << "clien quit...";
            //必须要先从epoll中移除fd，再关闭
            int res = epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
            if(res > 0)
            {
                LOG(LogLevel::INFO) << "epoll_ctl remove sockfd success: " << sockfd;
            }
            close(sockfd);
        }
        else
        {
            LOG(LogLevel::ERROR) << "recv error";
            int ret = epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
            if(ret > 0)
            {
                LOG(LogLevel::INFO) << "epoll_ctl remove sockfd success: " << sockfd;
            }
            close(sockfd);
        }


    }

    void Stop()
    {
        _isrunning = false;
    }

    ~EpollServer()
    {
        _listenSock->Close();
        if (_epfd > 0)
            close(_epfd);
    }

private:
    std::unique_ptr<Socket> _listenSock;
    bool _isrunning;
    int _epfd;

    struct epoll_event _revs[size];
};